import { Component, Host, ChangeDetectionStrategy, ChangeDetectorRef, EventEmitter, Output } from "@angular/core";
import { AppComponent } from "../../../../../app.component";
import { ReportingService } from "../../../reporting.service";
import { ActivatedRoute } from "@angular/router";
import { CriteriaPermissionsComponent } from "../criteriaPermissions.component";
import * as _ from 'lodash';
import { CriteriaComponent } from "../criteria.component";

@Component({
    templateUrl: 'baseCriteria.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class BaseCriteriaComponent extends CriteriaPermissionsComponent {
    public filterId: string;
    public type: number;
    public lvl1: string;
    public lvl2: string;
    public lvl2ShortName: string; //used for permission validation (different criteria groups have different validation)
    public criteria: any[];

    constructor(
        @Host() private criteriaComponent: CriteriaComponent,
        @Host() private rootComponent: AppComponent,
        private cdRef: ChangeDetectorRef,
        private route: ActivatedRoute,
        private toolsService: ReportingService) {
        super(cdRef);
    }

    ngOnInit() {
        this.route.parent.params.subscribe(parentParams => {
            this.type = parentParams['type'];
            this.filterId = parentParams['id'];
            this.route.params.subscribe(params => {
                this.lvl1 = params['lvl1'];
                this.lvl2 = params['lvl2'];
                this.toolsService.levels.subscribe(data => {
                    let lvl1Criteria = _.find(data, { id: this.lvl1 });
                    let lvl2Criteria = _.find(lvl1Criteria.childItems, { id: this.lvl2 });
                    this.lvl2ShortName = lvl2Criteria.shortName;
                    this.criteria = _(lvl2Criteria.baseCriteria as any[]).groupBy('category').map(function (items, key) {
                        return { key, items };
                    }).value();
                    
                    //set criteria avalability and check if we have at least one enabled
                    let anyEnabled: boolean = false;
                    this.criteria.forEach(criteria => {
                        criteria.items.forEach(item => {
                            item.enabled = super.isEnabled(this.lvl2ShortName, item.name);
                            anyEnabled = anyEnabled || item.enabled;
                        });
                    });
                    
                    this.cdRef.markForCheck();
                    this.criteriaComponent.selectAllAvailability.emit(anyEnabled);
                    this.rootComponent.finishLoading();
                });
            });
        });
    }
}